package org.csu.newpetstoreback.controller.front;

import org.csu.newpetstoreback.common.CommonResponse;
import org.csu.newpetstoreback.common.ResponseCode;
import org.csu.newpetstoreback.entity.Account;
import org.csu.newpetstoreback.service.AccountService;
import org.csu.newpetstoreback.service.impl.ZhenziSMS;
import org.csu.newpetstoreback.vo.AccountVO;
import org.csu.newpetstoreback.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/account/")
public class AccountController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private ZhenziSMS sms;

    //记得session需要的地方要全都用上
    //用户名和密码登录，返回用户信息
    @PostMapping("login")
    @ResponseBody
    public CommonResponse<AccountVO> login(
        @RequestParam String username,
        @RequestParam String password,
        HttpSession session){
        CommonResponse<AccountVO> response = accountService.getAccount(username,password);
        if(response.isSuccess()){
            session.setAttribute("login_account",response.getData());
        }
        return response;
    }

    //获取当前用户信息
    @PostMapping("get_login_account_info")
    @ResponseBody
    public CommonResponse<AccountVO> getLoginAccountInfo(HttpSession session){
        AccountVO loginAccount = (AccountVO)session.getAttribute("login_account");

        System.out.println(loginAccount);

        if(loginAccount != null){
            return CommonResponse.createForSuccess(loginAccount);
        }
        return CommonResponse.createForNotFound(1, "用户未登录，不能获取用户信息");
    }

    //更新用户信息
    @PostMapping("get_login_account_update")
    @ResponseBody
    public CommonResponse<Account> getLoginAccountUpdate(@RequestBody AccountVO accountVO, HttpSession session){
        AccountVO loginAccount = (AccountVO)session.getAttribute("login_account");//拿到当前对象的session信息
        if(loginAccount != null){
            accountVO.setUsername(loginAccount.getUsername());//要给传过来的信息加上本用户的username
            CommonResponse<Account> response = accountService.updateAccount(accountVO);
            session.setAttribute("login_account",response.getData());//将修改之后的信息放入session
            System.out.println(session.getAttribute("login_account"));
            return response;//返回更新后的信息
        }
        return CommonResponse.createForNotFound(ResponseCode.NEED_LOGIN.getCode(), "用户未登录，不能更新用户信息");
    }

    //注册，新增用户
    @PostMapping("register")
    @ResponseBody
    public CommonResponse<AccountVO> register(@RequestParam String username,
                                           @RequestParam String password,
                                           @RequestParam String email,
                                              HttpSession session){
        if(!(username.equals("") || password.equals(""))){
            CommonResponse<Account> temp = accountService.getAccountByName(username);
                // 若用户名可创建则注册用户
                if (!temp.isSuccess()) {
                    CommonResponse<AccountVO> response = accountService.insertAccount(username,password,email);
                    session.setAttribute("login_account",response.getData());//返回注册的用户信息
                    return response;//返回添加的用户信息
                }
                    return CommonResponse.createForNotFound(1, "用户名已被占用");

        }
        return CommonResponse.createForNotFound(2, "用户名和密码填写不规范");
    }

    //登出
    @PostMapping("signOut")
    @ResponseBody
    public CommonResponse<AccountVO> signOut(HttpSession session){
        AccountVO loginAccount = (AccountVO)session.getAttribute("login_account");//拿到当前session信息
        loginAccount = null;
        session.setAttribute("login_account",loginAccount);
            return CommonResponse.createForSuccessMessage("用户已注销");
    }

    //获取指定用户的所有订单
    @GetMapping("orders/{username}")
    @ResponseBody
    public CommonResponse<List<OrderVO>> getOrders(@PathVariable("username") String username){
        return accountService.getOrders(username);
    }

    @GetMapping("accounts/{username}")
    @ResponseBody
    public CommonResponse<Account> getAccountByName(@PathVariable("username") String username){
        return accountService.getAccountByName(username);
    }

    @GetMapping("accounts/username/{phone}")
    @ResponseBody
    public CommonResponse<Account> isPhoneIn(@PathVariable("phone") String phone){
        return accountService.isPhoneIn(phone);
    }

    //用户放上电话号码，拿到验证短信（登录用）
    @PostMapping("getNode/{phone}")
    @ResponseBody
    public CommonResponse<Map<String, Object>> getMessages(@PathVariable("phone") String phone,HttpSession session) throws Exception {

        System.out.println("要发短信的手机号：" + phone);

        CommonResponse<Account> response = accountService.isPhoneIn(phone);

        System.out.println("手机是否存在的：" + response);
        System.out.println("response.isSuccess()：" + response.isSuccess());

        if(response.isSuccess()){
            CommonResponse<Map<String, Object>> response2 = sms.sendMessage(phone,phone);
            if(response2.isSuccess()){
                session.setAttribute("message",response2.getData());
            }

            System.out.println("response2: " + response2);
            System.out.println("message: " + response2.getData());

            return response2;
        }
        else{

            System.out.println("手机号未注册");

            return CommonResponse.createForNotFound(2,"该电话号码未注册");
        }
    }

    //用户绑定手机号时的验证
    //要先判断手机号有没有在表里
    @PostMapping("tiePhone/{phone}")
    @ResponseBody
    public CommonResponse<Map<String, Object>> getMessagesTwo(@PathVariable("phone") String phone,HttpSession session) throws Exception{
        CommonResponse<Account> response2 = accountService.isPhoneIn(phone);
        if(!response2.isSuccess()){
            CommonResponse<Map<String, Object>> response = sms.sendMessage(phone,phone);
            if(response.isSuccess()){
                session.setAttribute("message",response.getData());
            }
            return response;
        }
        else{
            return CommonResponse.createForNotFound(2,"该电话号码已经被占用");
        }

    }

    //验证用户输入的验证码是否正确
    @PostMapping("verification/{cacheCode}")
    @ResponseBody
    public CommonResponse<Map<String, Object>> getAccountByName(@PathVariable("cacheCode") String cacheCode,HttpSession session)throws Exception{
        if(session.getAttribute("message")!=null){
            Map<String, Object> map = (Map<String, Object>)session.getAttribute("message");
            String messageId = String.valueOf(map.get("messageId"));
            return sms.checkMessage(messageId, cacheCode);
        }
        return CommonResponse.createForNotFound(2,"当前没有发送验证码");
    }

    //如果电话号码有对应用户，则在通过短信登录成功之后通过短信拿到用户信息
    //记得放入session
    @PostMapping("get_account_by_phone/{phone}")
    @ResponseBody
    public CommonResponse<AccountVO> getAccountByPhone(@PathVariable("phone") String phone,HttpSession session){
        CommonResponse<Account> response = accountService.isPhoneIn(phone);
        if(response.isSuccess()){
            CommonResponse<AccountVO> response2 = accountService.getAccountByPh(phone);
            session.setAttribute("login_account",response2.getData());//将返回的用户信息放入session
            return response2;
        }
        return CommonResponse.createForNotFound(1,"该手机号尚未注册");
    }

}
